package demo;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 *  二叉树的锯齿型层次遍历
 */
class Solution14 {
	public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
		List<List<Integer>> result = new ArrayList<>();
		if (root == null) {
			return result;
		}
		int level = 0;
		Queue<TreeNode> queue = new LinkedList<TreeNode>();
		queue.add(root);
		while (!queue.isEmpty()) {
			int size = queue.size();
			List<Integer> tmpList = new ArrayList<>();
			level++;
			for (int i = 0; i < size; i++) {
				TreeNode treeNode = queue.poll();
				tmpList.add(treeNode.val);
				if (treeNode.left != null) {
					queue.add(treeNode.left);
				}
				if (treeNode.right != null) {
					queue.add(treeNode.right);
				}
			}
			// 偶数层，需要List倒序
			if (level%2 == 0) {
				List<Integer> newList = new ArrayList<>(tmpList.size());
				int count = tmpList.size() - 1;
				for (int j = count; j >= 0; j--) {
					newList.add(tmpList.get(j));
				}
				result.add(newList);
			} else {
				result.add(tmpList);
			}
		}
		return result;
	}

	public static void main(String[] args) {
		TreeNode treeNode3 = new TreeNode(3);
		TreeNode treeNode9 = new TreeNode(9);
		TreeNode treeNode20 = new TreeNode(20);
		TreeNode treeNode15 = new TreeNode(15);
		TreeNode treeNode7 = new TreeNode(7);
		treeNode3.left = treeNode9;
		treeNode3.right = treeNode20;
		treeNode20.left = treeNode15;
		treeNode15.right = treeNode7;

		System.out.println(new Solution14().zigzagLevelOrder(treeNode3));
	}
}

